package com.chenjj.java.juc.tools.semaphore;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class People implements Runnable{
    private Semaphore semaphore;

    private People(){}

    public People(Semaphore semaphore){
        this.semaphore =semaphore;
    }


    @Override
    public void run() {
        boolean isAcquired = false;
        String name = Thread.currentThread().getId()+"";
        Random random = new Random();
        try{
            isAcquired = semaphore.tryAcquire();
            if (isAcquired){
                System.out.println(name+"正在食堂吃饭..");
                long s = System.currentTimeMillis();
                try {
                    Thread.sleep((int)Math.floor((random.nextDouble()*5000.0)));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                long e = System.currentTimeMillis();
                System.out.println(name+"吃完饭了，耗时：" + (e - s) + "ms");
            }else {
                System.err.println( name  + "因为食堂满了，没吃到饭");
            }
        }catch (Throwable e) {
            e.printStackTrace();
        }finally {
            if (isAcquired){
                semaphore.release();
            }
        }
    }
}
